/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package myheartsgame;

import java.io.*;
import java.net.*;

/**
 *
 * @author KaKa
 */
public class ServerTalking {
    
    ServerListener _listeningProcess;

    // Ham khoi tao cho 1 phien ket noi voi client
    ServerTalking(Socket listenSocket, String playerName) {        
        try {
            //Tao thread de lang nghe, ten ban dau la namePlayer
            _listeningProcess = new ServerListener(listenSocket, playerName);

        } catch (Exception e) {
        }
    }
}

class ServerListener implements Runnable {
    String _playerName;
    Socket _listeningSocket;
    Thread _thListening;
    // Bien kiem tra xem da lay ten cua client chua
    boolean _isGetClientName = false;
    public String _receivedMessage;

    ServerListener(Socket listSocket, String name) {
        try {
            _playerName = name;
            _listeningSocket = listSocket;
            _thListening = new Thread(this, name);
            _thListening.start();

        } catch (Exception ex) {
            System.out.println("Server listening process error");
        }
    }

    public void run() {

        BufferedReader br = null;
        InputStream is;
        try {
            is = _listeningSocket.getInputStream();
            br = new BufferedReader(new InputStreamReader(is));

            do {
                _receivedMessage = br.readLine();
                if (!_isGetClientName) {
                    int iIndexName = _receivedMessage.indexOf(" đã kết nối.");
                    if (iIndexName > 0) {
                        _playerName = _receivedMessage.substring(0, iIndexName);                        
                    }                    
                    _isGetClientName = true;
                }
                
                GlobalClass.chatBox += _receivedMessage + "\n";
                // Broadcast cho tat ca player tru player co thong tin _listeningSocket
                Server.BroadcastMessage(_receivedMessage, _listeningSocket);
                MainGame.RefreshChatBox();

            } while (true);

        } catch (IOException io) {
            // Xay ra mat ket noi thi giam so nguoi xuong
            --Server._iNumberPlayer;
            Server.RemoveClient(_listeningSocket);
            
            String outMessage =  ">>> " + _playerName + " đã rời khỏi trò chơi." + "\n";
            // Thong bao cho cac thanh vien khac
            Server.BroadcastMessage(outMessage, _listeningSocket);
            GlobalClass.chatBox += outMessage;
            MainGame.RefreshChatBox();
        }
        finally{

            try {
                // Dong ket noi,thread va socket lai
            br.close();
            _listeningSocket.close();
            _thListening.stop();
            }
            catch (IOException io){
                System.out.println("Close listener error");
            }
        }
    }
}
